package com.aerozhonghuan.logisticsmall.framework.hybrid;

import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.aerozhonghuan.foundation.eventbus.EventBusEvent;
import com.aerozhonghuan.hybrid.BaseActionHandler;
import com.aerozhonghuan.hybrid.XJsCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

/**
 * 描述 交互基础类
 * 作者 Zhang Yonghui
 * 创建日期 2019/1/21
 */
public abstract class SimpleActionHandler extends BaseActionHandler {

    private NewWebviewFragment fragment;
    private EventBusEvent eventBusEvent;

    public SimpleActionHandler(String action, NewWebviewFragment fragment) {
        super(action);
        this.fragment = fragment;
    }

    public Activity getActivity(){
        return fragment.getActivity();
    }

    public NewWebviewFragment getFragment(){
        return fragment;
    }


    /**
     * js调用原生action
     * @param action 动作名称
     * @param params 参数
     * @param callBack 回调
     */
    public abstract void handleAction(@NonNull final String action, @Nullable final JSONObject params, @Nullable final XJsCallback callBack);

    @Override
    public void handlAction(@NonNull final String action, @Nullable final JSONObject params, @Nullable final XJsCallback callBack, @NonNull String s1) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                handleAction(action, params, callBack);
            }
        });
    }

    /**
     * 处理js回调事件
     * @param params 参数
     * @param callBack 回调
     */
    public void onResult(Map<String, String> params, XJsCallback callBack){
        JSONObject result = null;
        try {
            result = new JSONObject();
            if (params != null && params.size() > 0) {
                for (Map.Entry<String, String> item : params.entrySet()) {
                    result.put(item.getKey(), item.getValue());
                }
            }
            if (callBack != null) {
                callBack.success(result);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            if (callBack != null) {
                callBack.failure(0, "json转换异常");
            }
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data){
    }

    public void onEvent(EventBusEvent event){
    }
}
